<template>
  <div class="tag-search">
    <el-select
      v-model="selectedTags"
      multiple
      filterable
      remote
      reserve-keyword
      placeholder="请输入标签名称进行搜索"
      :remote-method="remoteMethod"
      :loading="loading"
      style="width: 100%"
      @change="handleTagSelect"
    >
      <el-option
        v-for="item in tagOptions"
        :key="item.labelId"
        :label="item.labelName"
        :value="item.labelName">
        <span class="tag-option" :style="{ color: item.color || '#409EFF' }">{{ item.labelName }}</span>
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { listLabel } from "@/api/note/noteLabel";

export default {
  name: "TagSearch",
  props: {
    value: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      selectedTags: [],
      tagOptions: [],
      loading: false,
      allTags: []
    };
  },
  watch: {
    value: {
      handler(newVal) {
        if (newVal) {
          // 将逗号分隔的字符串转换为数组
          this.selectedTags = newVal.split(',').map(tag => tag.trim()).filter(tag => tag);
        } else {
          this.selectedTags = [];
        }
      },
      immediate: true
    }
  },
  created() {
    this.loadAllTags();
  },
  methods: {
    // 加载所有标签
    async loadAllTags() {
      this.loading = true;
      try {
        const response = await listLabel({});
        this.allTags = response.rows || [];
        this.tagOptions = this.allTags;
      } catch (error) {
        console.error("加载标签失败:", error);
      } finally {
        this.loading = false;
      }
    },
    
    // 远程搜索方法
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.tagOptions = this.allTags.filter(item => {
            return item.labelName.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.tagOptions = this.allTags;
      }
    },
    
    // 处理标签选择
    handleTagSelect(value) {
      // 将数组转换为逗号分隔的字符串
      const tagsString = value.join(',');
      this.$emit('input', tagsString);
      this.$emit('change', tagsString);
    }
  }
};
</script>

<style scoped>
.tag-search {
  width: 100%;
}

.tag-option {
  font-weight: bold;
}
</style>